package com.baiyue.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author 伍波
 * @date 2023/8/8 17:21
 */

public class AESUtil {
    private static final Logger logger = LoggerFactory.getLogger(AESUtil.class);

    public static String AES_KEY = "2023030219170123";
    public static String AES_IV = "1234567812345678";

    //加密数据
    public static String encrypt(String data, String secret, String iv) {
        byte[] crypted = null;
        secret = StringUtils.isBlank(secret) ? AES_KEY : secret;
        iv = StringUtils.isBlank(iv) ? AES_IV : iv;
        try {
            //1. 使用 0 来补齐数据
            data = StringUtils.rightPad(data, 16, "\0");
            //2. 设置加密方式
            SecretKeySpec skey = new SecretKeySpec(secret.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skey, new IvParameterSpec(iv.getBytes()));
            //3. 数据加密
            crypted = cipher.doFinal(data.getBytes());
            //4. base64加密
            if (crypted != null) {
                return Base64.getEncoder().encodeToString(crypted);
            }
        } catch (Exception e) {
            logger.error(String.format("AESUtil.encrypt，data：%s，AES加密异常", data), e);
        }
        return null;
    }

    //解密数据
    public static String decrypt(String phone, String secret, String iv) {
        if (StringUtils.isEmpty(phone)) {
            return phone;
        }
        byte[] output = null;
        secret = StringUtils.isBlank(secret) ? AES_KEY : secret;
        iv = StringUtils.isBlank(iv) ? AES_IV : iv;
        try {
            //1. 设置加密方式
            SecretKeySpec skey = new SecretKeySpec(secret.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(iv.getBytes()));
            //2. base64解密，并AES解密
            output = cipher.doFinal(Base64.getDecoder().decode(phone));
            if (output != null) {
                return new String(output).trim();
            }
        } catch (Exception e) {
            logger.error(String.format("AESUtil.decrypt，phone：%s，AES解密异常", phone), e);
        }
        return null;
    }

}
